<template>
  <div>
    <el-button type="primary" @click="dialogFormVisible = true">
      我要请假
    </el-button>
    <el-dialog v-model="dialogFormVisible" title="请假信息">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="请假理由" prop="leavereason">
          <el-input v-model="ruleForm.leavereason" />
        </el-form-item>

        <el-form-item label="开始时间" prop="start">
          <el-date-picker
            v-model="ruleForm.start"
            type="datetime"
            placeholder="选择请假开始日期"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="end">
          <el-date-picker
            v-model="ruleForm.end"
            type="datetime"
            placeholder="请选择结束时间"
          />
        </el-form-item>

        <el-form-item label="附件" prop="extend">
          <el-upload
            v-model:file-list="fileList"
            action="/api/uploads"
            name="filename"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :auto-upload="false"
            :on-success="success"
            ref="uploadRef"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >请假
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadInstance,
} from "element-plus";
import { addLeave } from "@/service/leaveService";
const fileList = ref<any>([]); //显示的图片集合
const uploadRef = ref<UploadInstance>(); //图片上传的组件名称
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const dialogFormVisible = ref(false);
const ruleFormRef = ref<FormInstance>();
let emits = defineEmits(["addData1ListItem"]);
let successList: any = []; //上传成功的集合
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const success = async (response: any) => {
  //图片上传成功的方法
  successList.push(response.url); //
  if (successList.length == fileList.value.length) {
    //表示全部上传成功
    console.log(ruleForm); //但是里面没有extend没有值
    let { data } = await addLeave({
      ...ruleForm,
      extend: successList.join(","),
    });
    if (data.code == 200) {
      let info = data.result[0]; //新增的对象
      resetForm(ruleFormRef.value); //关闭弹出层
      emits("addData1ListItem", info);
    }
    resetForm(ruleFormRef.value);
    fileList.value = []; //清空图列表
  }
};
const ruleForm = reactive({
  leavereason: "",
  start: "",
  end: "",
  extend: "",
});
let checkDate = (rule: any, value: any, callback: any) => {
  let start = new Date(ruleForm.start);
  let end = new Date(value);
  if (start > end) {
    callback(new Error("开始时间不能大于结束时间"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  leavereason: [
    { required: true, message: "理由不能为空", trigger: "blur" },
    { min: 2, max: 50, message: "长度只能是2到50位", trigger: "blur" },
  ],
  start: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
  end: [
    { required: true, message: "结束时间不能为空", trigger: "blur" },
    { validator: checkDate, trigger: "change" },
  ],
});
//提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      //表单验证通过
      //
      if (fileList.value.length) {
        //有图片需要上传
        uploadRef.value!.submit();
      } else {
        //没有图片需要上传
        let { data } = await addLeave({
          ...ruleForm,
        });
        if (data.code == 200) {
          //表示新增成功
          let info = data.result[0]; //新增的对象
          resetForm(ruleFormRef.value); //关闭弹出层
          emits("addData1ListItem", info);
        }
        resetForm(ruleFormRef.value);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogFormVisible.value = false;
};
</script>
